/*
题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-deepest-leaves/description/?envType=daily-question&envId=2025-04-04
*/

//题解代码:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* ans;
    int maxh = 0;
    void dfs1(TreeNode* root,int deep){
        if(!root) return;
        maxh = max(maxh,deep);
        dfs1(root->left,deep+1);
        dfs1(root->right,deep+1);
    }
    int dfs2(TreeNode* root,int deep){
        if(!root) return -1;
        int lh = dfs2(root->left,deep+1);
        int rh = dfs2(root->right,deep+1);
        if(lh==-1 && rh==-1 && deep==maxh) ans = root;
        if(lh==maxh && rh==maxh) ans = root;
        return max(deep,max(lh,rh));
    }
    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        dfs1(root,0);
        dfs2(root,0);
        return ans;
    }
};
